package com.example.config;


import com.example.pojo.Result;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.Serializable;

/**
 * @author crt
 */
@Slf4j
@ControllerAdvice
public class ControllerAdviceConfiguration {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Result<Serializable> exception(Exception e, HttpServletResponse response) {
        log.error(e.getLocalizedMessage());
        e.printStackTrace();
        responseForJson(response);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Result<Serializable> exception(MethodArgumentNotValidException e, HttpServletResponse response) {
        log.warn(e.getLocalizedMessage());
        responseForJson(response);
        return Result.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    private void responseForJson(HttpServletResponse response) {
        // 设置响应的字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
    }
}
